<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="users.query.username"
        class="filter-item"
        placeholder="用户名"
        style="width: 120px;"
        clearable/>
      <el-input
        v-model="users.query.nickname"
        placeholder="昵称"
        class="filter-item"
        style="width: 120px;"
        clearable/>
      <el-input
        v-model="users.query.phone"
        placeholder="手机号"
        class="filter-item"
        style="width: 120px;"
        clearable/>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-search"
        @click="() => findUserPage()">查询
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="() => saveUserOpen('add')">添加
      </el-button>
    </div>
    <v-plain-table :data="users" @change="change">
      <template slot="expand" slot-scope="{scope}">
        <el-button type="text" @click="() => saveUserOpen('update',scope.row)">编辑</el-button>
        <el-button type="text" @click="()=>authorizationOpen(scope.row.id)">授权</el-button>
      </template>
    </v-plain-table>
    <el-dialog :title="userDialog.title" :visible.sync="userDialog.dialogFormVisible" width="40%" size="mini" @close="dialogClose('userDialog',userDialog.dialogFormVisible)">
      <el-form ref="userDialog" :model="userDialog.user" :rules="userDialog.rules" >
        <el-form-item :label-width="formLabelWidth" label="用户名" prop="username">
          <el-input v-model="userDialog.user.username" autocomplete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="昵称" prop="nickname">
          <el-input v-model="userDialog.user.nickname" autocomplete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="手机号" prop="phone">
          <el-input v-model="userDialog.user.phone" autocomplete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="性别" >
          <el-radio-group v-model="userDialog.user.gender">
            <el-radio label="男" />
            <el-radio label="女" />
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialog.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUser('userDialog')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="authorizationDialog.title" :visible.sync="authorizationDialog.dialogFormVisible" width="30%" size="mini" @close="dialogClose(null,authorizationDialog.dialogFormVisible)">
      <template>
        <el-transfer
          v-model="authorizationDialog.transfer.owned"
          :props="authorizationDialog.transfer.props"
          :data="authorizationDialog.transfer.data"
          :titles="authorizationDialog.transfer.titles"/>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="authorizationDialog.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUserRole()">确 定</el-button>
      </div>
    </el-dialog>
</div></template>

<script>
import vPlainTable from '@/components/plain-table'
import { getUserPage, saveUser } from '@/api/sys/user'
import {
  getAllList,
  getRoleIdListByUserId
} from '@/api/sys/role'
import {
  saveUserRole
} from '@/api/sys/userRole'
export default {
  name: 'Index',
  components: {
    vPlainTable
  },
  data() {
    var phonevalidator = (rule, value, callback) => {
      const reg = /(?:^1[3456789]|^9[28])\d{9}$/
      const flag = reg.test(value)
      if (!flag) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }

    return {
      authorizationDialog: {
        title: '角色授权',
        dialogFormVisible: false,
        transfer: {
          titles: ['未拥有', '已拥有'],
          props: {
            key: 'id',
            label: 'roleName'
          },
          userId: '',
          data: [],
          owned: []
        }
      },
      userDialog: {
        title: '',
        dialogFormVisible: false,
        user: { gender: '男', username: '', nickname: '', phone: '', id: '' },
        rules: {
          username: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 1, max: 50, message: '长度在 1 到 50个字符', trigger: 'blur' }
          ],
          phone: [
            { validator: phonevalidator, trigger: 'blur' }

          ],
          nickname: [
            { required: true, message: '请输入用户昵称', trigger: 'blur' },
            { min: 1, max: 50, message: '长度在 1 到 50个字符', trigger: 'blur' }
          ]
        }
      },
      users: {
        header: [{
          label: '用户名',
          key: 'username'
        },
        {
          label: '昵称',
          key: 'nickname'
        },
        {
          label: '性别',
          key: 'gender'
        },
        {
          label: '创建时间',
          key: 'creatTime'
        },
        {
          label: '修改时间',
          key: 'updateTime'
        }],
        body: {
          current: 1,
          size: 10,
          total: 0,
          records: []
        },
        operation: true,
        query: {
          username: '',
          nickname: '',
          phone: ''
        }
      }, formLabelWidth: '70px'
    }
  },
  mounted: function() {
    this.findUserPage()
    this.findAllRoles()
  },
  methods: {
    findUserPage() {
      const userpage = {
        current: this.users.body.current,
        size: this.users.body.size,
        username: this.users.query.username,
        nickname: this.users.query.nickname,
        phone: this.users.query.phone
      }
      getUserPage(userpage).then(resp => {
        this.users.body = resp.result
      })
    }, change(current) {
      this.roles.body.current = current
      this.getAllPage()
    }, dialogClose(formName, dialogFormVisible) {
      dialogFormVisible = false
      if (formName != null) {
        this.$refs[formName].resetFields()
        this.userDialog.user = { gender: '男' }
      }
    }, saveUserOpen(flag, user) {
      if (flag === 'update') {
        this.userDialog.title = '用户编辑'
        this.userDialog.user.id = user.id
        this.userDialog.user.username = user.username
        this.userDialog.user.nickname = user.nickname
        this.userDialog.user.phone = user.phone
        this.userDialog.user.gender = user.gender
      }
      if (flag === 'add') {
        this.userDialog.title = '新增用户'
      }
      this.userDialog.dialogFormVisible = true
    }, submitUser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveUser(this.userDialog.user).then(resp => {
            this.userDialog.dialogFormVisible = false
            this.findUserPage()
            this.$message.success('保存成功')
          })
          return true
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }, authorizationOpen(id) {
      this.findRoleIdList(id)
      this.authorizationDialog.transfer.userId = id
      this.authorizationDialog.dialogFormVisible = true
    }, findAllRoles() {
      getAllList().then(resp => {
        this.authorizationDialog.transfer.data = resp.result
      })
    }, findRoleIdList(id) {
      getRoleIdListByUserId(id).then(resp => {
        this.authorizationDialog.transfer.owned = resp.result
      })
    },
    submitUserRole() {
      const map = { userId: this.authorizationDialog.transfer.userId, roleIds: this.authorizationDialog.transfer.owned }
      saveUserRole(map).then(resp => {
        this.authorizationDialog.dialogFormVisible = false
      })
    }
  }
}
</script>
